<template>
  <el-dialog v-model="dialogVisible" title="新增乡村负责人信息" width="500" @submit.prevent>
    <el-form>
      <el-form-item label="负责人姓名">
        <el-input v-model="username" />
      </el-form-item>
      <el-form-item label="负责人账号">
        <el-input v-model="realname" />
      </el-form-item>
      <el-form-item label="负责乡村">
        <el-select v-model="villageId" placeholder="请选择乡村">
          <el-option
            v-for="item of villages"
            :key="item.villageId"
            :label="item.villageName"
            :value="item.villageId + ''"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="UserDialog">
import type { VillageInfo } from '@/api/village.model'
import useErrorMessage from '@/hooks/useErrorMessage'
import { ElMessage } from 'element-plus'
import { villageList } from '@/api/village'
import { addUser } from '@/api/user'

const mProps = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'refresh'])

const dialogVisible = computed({
  get() {
    return mProps.visible
  },
  set(value) {
    emit('update:visible', value)
  }
})

const username = ref<string>('')
const realname = ref<string>('')
const villageId = ref<string>('')
const villages = ref<VillageInfo[]>([])

const getVillageList = async () => {
  try {
    const { data } = await villageList()
    villages.value = data.data
  } catch (error) {
    useErrorMessage(error)
  }
}
getVillageList()

const handleSubmit = async () => {
  const _username = username.value.trim()
  const _realname = realname.value.trim()
  if (!_username) {
    ElMessage.warning('请输入负责人姓名')
    return
  }
  if (!_realname) {
    ElMessage.warning('请输入负责人账号')
    return
  }
  if (!villageId.value) {
    ElMessage.warning('请选择乡村')
    return
  }
  try {
    const data = {
      username: _username,
      realname: _realname,
      villageId: villageId.value
    }
    await addUser(data)
    ElMessage.success('添加成功')
    emit('refresh')
    dialogVisible.value = false
  } catch (error) {
    useErrorMessage(error)
  }
}
</script>

<style lang="scss" scoped></style>
